﻿using System.Collections.Generic;
using System.Data;
using MingleReport.HttpRequests;
using MySql.Data.MySqlClient;

namespace MingleReport.Services
{
    public class StoryCardRepository : IStoryCardRepository
    {
        private readonly IMingleSession session;
        private readonly IHttpRequestFactory httpRequestFactory;
        private readonly XmlDocumentParser<StoryCard> xmlDocumentParser;

        public StoryCardRepository(IMingleSession session,
                                   IHttpRequestFactory httpRequestFactory,
                                   XmlDocumentParser<StoryCard> xmlDocumentParser)
        {
            this.session = session;
            this.httpRequestFactory = httpRequestFactory;
            this.xmlDocumentParser = xmlDocumentParser;
        }

        public virtual List<StoryCard> GetAllStoryCardsByProjectId()
        {
            MingleHttpStoryCardRequest request = httpRequestFactory.GetStoryCardRequest(
                session.ServerUrl, session.ProjectId, session.LoginCookie);
            request.Create();
            return xmlDocumentParser.Parse(request.GetResponse());
        }

        public List<string> GetAllCardTypesByProjectId()
        {
            List<string> cardTypes = new List<string>();
            List<StoryCard> cards = GetAllStoryCardsByProjectId();
            foreach (StoryCard card in cards)
            {
                if (!cardTypes.Contains(card.Type))
                {
                    cardTypes.Add(card.Type);
                }
            }
            return cardTypes;
        }

        //TODO : add a sqlrunner class
        public List<string> GetAllCardPropertiesByCardType(string type)
        {
            string connectionString = "SERVER='" + SQLUserSettings.DB_SERVER + "';" +
                                      "DATABASE='" + SQLUserSettings.DATABASE + "';" +
                                      "UID='" + SQLUserSettings.UID + "';";
           
            MySqlConnection conn = new MySqlConnection(connectionString);
            conn.Open();
            MySqlDataAdapter da =
                new MySqlDataAdapter(
                    "SELECT property_definitions.name FROM card_types_property_definitions, property_definitions, card_types where card_types_property_definitions.card_type_id=card_types.id and card_types_property_definitions.property_definition_id = property_definitions.id and card_types.name='" +
                    type + "';", conn);

            DataSet ds = new DataSet("Properties");
            da.Fill(ds, "Properties");
            conn.Close();
            conn.Dispose();

            DataTable dt = ds.Tables[0];

            List<string> propertyNames = new List<string>();
            foreach (DataRow dr in dt.Rows)
            {
                propertyNames.Add(dr["name"].ToString());
            }
            return propertyNames;
        }
    }
}